import { MIN_PORT, MAX_PORT } from './constants'

const numbers = []

const getIpAddress = () => {
  return 'mengning.com.cn'
}

export const generateRandomString = length => {
  const chars =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=-'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

const generateUniqueRandomNumbers = () => {
  if (numbers.length >= MAX_PORT - MIN_PORT + 1) {
    throw new Error('Count cannot be greater than the range of numbers.')
  }

  for (let i = 0; i < 1000; i++) {
    const randomNumber =
      Math.floor(Math.random() * (MAX_PORT - MIN_PORT + 1)) + MIN_PORT
    if (!numbers.includes(randomNumber)) {
      numbers.push(randomNumber)
      return randomNumber
    }
  }
  return -1
}

export const getsshCommand = user => {
  const port = generateUniqueRandomNumbers()
  const ip = getIpAddress()
  return [`ssh -p ${port} ${user}@${ip}`, port]
}
